package com.zsl.controller;

import com.alibaba.fastjson.JSON;
import com.zsl.model.Users;
import com.zsl.service.UsersService;
import com.zsl.service.impl.UsersServiceImpl;
import com.zsl.util.Base64Encoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


public class AddUser extends HttpServlet {
    private final UsersService usersService = new UsersServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 获取表单参数
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        String hobby = request.getParameter("hobby");
        Users user = new Users(null,uname, Base64Encoder.encode(pwd), hobby,null);
        PrintWriter out = response.getWriter();
        Map<String, Object> map = new HashMap<String, Object>();
        // 传入写入用户Service
        try {
            usersService.addUserService(user);
            map.put("line", 1);
            map.put("success", 1);
            response.setStatus(200);
        } catch (Exception e) {
            map.put("line", 0);
            map.put("success", 0);
            response.setStatus(500);
            e.printStackTrace();
        } finally {
            // 返回提示信息
            out.write(JSON.toJSONString(map));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
